<template>
  <div class="coupon-wrapper">
    <div class="tabs">
      <div
        class="tab-item"
        v-for="(item, index) of tabs"
        :key="index"
        @click="tabItemClick(index)"
        :class="{'active': activeIndex === index}"
      >{{item}}</div>
      <div class="tab-angle" :style="{left: anLeft +'rem'}">
        <img src="@/assets/images/icon_sjb.png" alt />
      </div>
    </div>
    <Scroll class="coupon-scroll" ref="couponScroll" v-if="couponList.length" :data="couponList">
      <div class="content">
        <div class="inner">
          <div v-for="(item, index) of couponList" :key="index">
            <panel-coupon
              class="panel-coupon"
              :couponInfo="item"
              :showCount="user.identity_type ? true : false"
              :showShare="user.identity_type ? true : false"
              @shareClick="handleShareClick"
              @useCouponDetail="$router.push({ path: '/my/coupon/coupon-detail', query: {coupon: JSON.stringify(item)} })"
              @useCoupon="handleUseCoupon(item)"
            />
          </div>
        </div>
      </div>
    </Scroll>
    <no-result v-else :src="require('@/assets/images/1-zwnr.png')" msg="暂无优惠券" />
    <transition name="slide">
      <router-view @success="handleSuccess"></router-view>
    </transition>
  </div>
</template>
<script>
import NoResult from '@/components/no-result/no-result'
import PanelCoupon from './coupon/panel-coupon'
import Scroll from '@/components/scroll/scroll'
import { getCouponList, getUserCouponList } from '@/api/my'
import ConfigList from '@/views/my/mixins/config-list'
import wx from 'weixin-js-sdk'
const ERR_OK = 200

export default {
  components: {
    NoResult,
    PanelCoupon,
    Scroll
  },
  mixins: [ConfigList],
  data () {
    return {
      tabs: ['全场通用', '品牌优惠券'],
      activeIndex: 0,
      anLeft: 0.8,
      couponList: [],
      type: 1,
      user: null
    }
  },
  created () {
    if (this.$route.query.coupon_type) {
      this.activeIndex = parseInt(this.$route.query.coupon_type) - 1
      this.type = 2
      this.anLeft = 2.8
    }
    this.user = this.$store.getters.userInfo
      ? this.$store.getters.userInfo
      : JSON.parse(localStorage.getItem('USER'))
    if (this.user && this.user.identity_type) {
      this._getCouponList(this.type, this.$route.query.information_id)
    } else {
      this._getUserCouponList(this.type, this.$route.query.information_id)
    }
  },
  beforeRouteLeave (to, from, next) {
    // ...
    this.$emit('success')
    next()
  },
  computed: {
    userInfo () {
      const userInfo = this.$store.getters.userInfo
        ? this.$store.getters.userInfo
        : JSON.parse(localStorage.getItem('USER'))
      return userInfo
    }
  },
  methods: {
    handleSuccess () {
      this.couponList = []
      if (this.user && this.user.identity_type) {
        this._getCouponList(this.type, this.$route.query.information_id)
      } else {
        this._getUserCouponList(this.type, this.$route.query.information_id)
      }
    },
    handleUseCoupon (item) {
      if (item.count > 0) {
        this.$router.push({
          path: '/my/coupon/use-coupon',
          query: {
            user_coupon_id: item.user_coupon_id,
            couponId: item.id,
            brand_name:
              parseInt(item.type) === 1
                ? encodeURIComponent('全场通用')
                : item.brand_name,
            shop_id: item.shop_id,
            verify_code: encodeURIComponent(item.verify_code),
            discount_money: item.discount_money,
            discount_limit: item.discount_limit,
            start_at: item.start_at,
            end_at: item.end_at,
            type: item.type
          }
        })
      } else {
        this.$toast('优惠券数量不够，暂不能使用~')
      }
    },
    // handleShowShare (item) {
    //   const userInfo = this.$store.getters.userInfo
    //   const getTime = new Date(item.created_at.replace(/-/g, '/')).getTime()
    //   const designerTime = new Date(
    //     userInfo.created_at.replace(/-/g, '/')
    //   ).getTime()
    //   if (userInfo) {
    //     if (userInfo.identity_type) {
    //       if (getTime < designerTime && item.type !== 1) {
    //         return false
    //       } else if (getTime >= designerTime || item.type === 1) {
    //         return true
    //       }
    //     } else {
    //       return false
    //     }
    //   } else {
    //     return false
    //   }
    // },
    hasExpired (couponInfo) {
      const endTime = new Date(couponInfo.end_at.replace(/-/g, '/')).getTime()
      const nowTime = new Date().getTime()
      if (endTime < nowTime) {
        return true
      } else {
        return false
      }
    },
    handleShareClick (couponInfo) {
      if (this.user.identity_type) {
        if (couponInfo.count > 0 && !this.hasExpired(couponInfo)) {
          wx.miniProgram.getEnv(ress => {
            if (ress.miniprogram) {
              const designerId = JSON.parse(localStorage.getItem('USER'))
                .designer_id
              wx.miniProgram.navigateTo({
                url: `/pages/share/share?couponId=${couponInfo.id}&designerId=${designerId}`
              })
            }
          })
        } else if (couponInfo.count > 0 && this.hasExpired(couponInfo)) {
          // console.log('优惠券已过期，暂不能分享~')
          this.$toast('优惠券已过期，暂不能分享~')
        } else {
          this.$toast('优惠券数量不够，暂不能分享~')
        }
      } else {
        return false
      }
    },
    tabItemClick (index) {
      this.activeIndex = index

      switch (index) {
        case 0:
          this.anLeft = 0.8
          this.type = 1
          break
        case 1:
          this.type = 2
          this.anLeft = 2.8
          break
      }
      if (this.user.identity_type) {
        this._getCouponList(this.type).then(res => {
          if (res.code === ERR_OK) {
            if (this.$refs.couponScroll) {
              this.$refs.couponScroll.scrollTo(0, 0)
            }
          }
        })
      } else {
        this._getUserCouponList(this.type).then(res => {
          if (res.code === ERR_OK) {
            this.$refs.couponScroll.scrollTo(0, 0)
          }
        })
      }
    },
    _getCouponList (type, informationId) {
      return getCouponList(type, informationId)
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            res.data.sort(function (o1, o2) {
              return o2.count - o1.count
            })
            this.couponList = res.data
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    _getUserCouponList (type, informationId) {
      return getUserCouponList(type, informationId)
        .then(res => {
          if (res.code === ERR_OK) {
            console.log(res)
            res.data.sort(function (o1, o2) {
              return o2.count - o1.count
            })
            this.couponList = res.data
            return Promise.resolve(res)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/mixin.scss";
@include slideEnter();
.coupon-wrapper {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  background: #f7f7f7;
  touch-action: none;
  .coupon-scroll {
    position: absolute;
    top: 1rem;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
  .tabs {
    width: 100%;
    height: 1rem;
    background: rgba(255, 255, 255, 1);
    padding: 0 0.36rem;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-start;
    position: relative;
    .tab-item {
      font-size: 0.28rem;
      line-height: 0.28rem;
      font-family: PingFang SC;
      font-weight: 300;
      color: rgba(51, 51, 51, 1);
      text-align: center;
      margin-right: 0.71rem;
      padding: 0.36rem 0;
      &.active {
        font-weight: bold;
      }
    }
    .tab-angle {
      position: absolute;
      bottom: 0;
      width: 0.12rem;
      height: 0.06rem;
      transition: all 0.15s;
      img {
        width: 100%;
        vertical-align: top;
      }
    }
  }
  .content {
    width: 100%;
    padding: 0.42rem 0.45rem;
    box-sizing: border-box;
    .inner {
      padding-bottom: 1rem;
    }
    .panel-coupon {
      margin-bottom: 0.52rem;
    }
  }
}
</style>
